﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace ServiceCore.Tool.Post
{
      

    public class Http_Helper
    {
        public static string HttpGet(string url)
        {

            HttpWebRequest webrequest =
                (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.Method = "Get";
            webrequest.ContentType = "application/json"; //无关的请求头在本文中都省略掉了 
            //webrequest.Headers.Add("Access-Token", "Sinopec-Station");   
            HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312")); 
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        public static string HttpPost(string url, string postjson)
        {

            HttpWebRequest webrequest =
                (HttpWebRequest)HttpWebRequest.Create(url);
            webrequest.Method = "POST";
            webrequest.ContentType = "application/json"; //无关的请求头在本文中都省略掉了 
            //webrequest.Headers.Add("Access-Token", "Sinopec-Station"); 
            string postData = postjson;
            byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
            webrequest.ContentLength = postdatabyte.Length;
            Stream stream = webrequest.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312")); 
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        /// <summary>
        /// 调用接口的方法
        /// </summary>
        /// <param name="url">调用的接口地址</param>
        /// <param name="postValues">参数集合</param>
        /// <returns></returns>
        public static string Redirect(string url, NameValueCollection postValues, ref int PostRepCode)
        {
            try
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "text/html";//"application/x-www-form-urlencoded";
                request.Credentials = CredentialCache.DefaultCredentials;
                var data = EncodePars(postValues);
                WriteRequestData(request, data);
                var response = request.GetResponse() as HttpWebResponse;
                PostRepCode = (int)response.StatusCode;
                var responseStream = response.GetResponseStream();
                //var encoding = new UTF8Encoding();
                var reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                var rValue = reader.ReadToEnd();
                reader.Close();
                responseStream.Close();
                return rValue;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //AddPushLog("", url + ":_" + ex.ToString(), DateTime.Now, DateTime.Now, "0", "");
                return "";
            }
        }
        /// <summary>
        /// 请求数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="data"></param>
        private static void WriteRequestData(HttpWebRequest request, byte[] data)
        {
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
        }
        /// <summary>
        /// 编码方式
        /// </summary>
        /// <param name="Pars"></param>
        /// <returns></returns>
        private static byte[] EncodePars(NameValueCollection Pars)
        {
            return Encoding.UTF8.GetBytes(ParsToString(Pars));
        }
        /// <summary>
        /// 参数转为字符串
        /// </summary>
        /// <param name="Pars"></param>
        /// <returns></returns>
        private static String ParsToString(NameValueCollection Pars)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in Pars.Keys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }
                sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
            }
            return sb.ToString();
        } 
    }

    public class upload_http
    {
        /// <summary>
        /// POST文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files">文件路径</param>
        /// <param name="postdata">参数</param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string HttpUploadFile(string url, IFormFile file, Dictionary<string, string> postdata, Encoding encoding)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            HttpWebRequest request = CreateWebRequest(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true; ;
            request.AllowAutoRedirect = this.AllowAutoRedirect;
            if (Cookie != null)
                request.CookieContainer = this.Cookie;
            request.Credentials = CredentialCache.DefaultCredentials;
            using (Stream stream = request.GetRequestStream())
            {
                //1.1 key/value
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                if (postdata != null)
                {
                    foreach (string key in postdata.Keys)
                    {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, postdata[key]);
                        byte[] formitembytes = encoding.GetBytes(formitem);
                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }
                //1.2 file
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                byte[] buffer = new byte[4096];
                int bytesRead = 0;

                stream.Write(boundarybytes, 0, boundarybytes.Length);
                string header = string.Format(headerTemplate, "media", file.FileName);
                byte[] headerbytes = encoding.GetBytes(header);
                stream.Write(headerbytes, 0, headerbytes.Length);
                using (Stream fileStream = file.OpenReadStream())
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                }

                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                return stream.ReadToEnd();
            }
        }
        protected HttpWebRequest CreateWebRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //request.ContentType = "text/html;charset=UTF-8";
            request.ContentType = this.ContentType;
            if (this.Cookie != null)
                request.CookieContainer = this.Cookie;
            if (string.IsNullOrEmpty(this.AcceptLanguage))
            {
                WebHeaderCollection myWebHeaderCollection = request.Headers;
                myWebHeaderCollection.Add("Accept-Language", this.AcceptLanguage);
            }
            request.Accept = this.Accept;
            request.UseDefaultCredentials = true;
            request.UserAgent = this.UserAgent;
            request.Timeout = this.TimeOut;
            request.AllowAutoRedirect = this.AllowAutoRedirect;
            //this.SetCertificatePolicy();
            return request;
        }
        /// <summary>
        /// 设置cookie
        /// </summary>
        private CookieContainer cookie;

        public CookieContainer Cookie
        {
            get { return cookie; }
            set { cookie = value; }
        }

        /// <summary>
        /// 是否允许重定向
        /// </summary>
        private bool allowAutoRedirect = true;
        /// <summary>
        /// 是否允许重定向(默认:true)
        /// </summary>
        public bool AllowAutoRedirect
        {
            get { return allowAutoRedirect; }
            set { allowAutoRedirect = value; }
        }

        /// <summary>
        /// contentType
        /// </summary>
        private string contentType = "application/x-www-form-urlencoded";
        /// <summary>
        /// 设置contentType(默认:application/x-www-form-urlencoded)
        /// </summary>
        public string ContentType
        {
            get { return contentType; }
            set { contentType = value; }
        }

        /// <summary>
        /// accept
        /// </summary>
        private string accept = "*/*";
        /// <summary>
        /// 设置accept(默认:*/*)
        /// </summary>
        public string Accept
        {
            get { return accept; }
            set { accept = value; }
        }

        /// <summary>
        /// 过期时间（默认：30000）
        /// </summary>
        private int timeOut = 30000;

        public int TimeOut
        {
            get { return timeOut; }
            set { timeOut = value; }
        }

        private string userAgent;
        /// <summary>
        /// 
        /// </summary>
        public string UserAgent
        {
            get { return userAgent; }
            set { userAgent = value; }
        }
        private string acceptLanguage;
        /// <summary>
        /// 接受的语言
        /// </summary>
        public string AcceptLanguage
        {
            get { return acceptLanguage; }
            set { acceptLanguage = value; }
        }
        //private void SetCertificatePolicy()
        //{
        //    ServicePointManager.ServerCertificateValidationCallback
        //               += RemoteCertificateValidate;
        //}
    }
}
